#pragma once

#include <iostream>
#include <string>
#include <memory>
#include <sys/select.h>
#include <poll.h>
#include <sys/types.h>
#include "Log.hpp"
#include "Socket.hpp"

using namespace SocketModule;
using namespace LogModule;

#define MAX 4096

const int gdefalutfd = -1;

class PollServer
{
public:
    PollServer(uint16_t newport)
        : _port(newport), _listen_socket(std::make_unique<TcpSocket>()), _is_running(false)
    {
    }

    void Init()
    {
        _listen_socket->BulidTcpSocket(_port);
        for (int i = 0; i < NUM; i++)
        {
            _fds[i].fd = gdefalutfd;
            _fds[i].events = 0;
            _fds[i].revents = 0;
        }    

        // Add listensockfd to array
        _fds[0].fd = _listen_socket->Fd();
        _fds[0].events |= POLLIN;
    }

    void Start()
    {
        _is_running = true;
        while (_is_running)
        {
            // 定义时间
            int timeout = -1;

            // poll等待
            int n = poll(_fds, MAX, timeout);
            switch (n)
            {
            case 0:
                std::cout << "select timeout" << std::endl;
                break;
            case -1:
                perror("select");
                break;
            default:
                // 有事件就绪
                std::cout << "有事件就绪: " << std::endl;
                HandleEvents(rfds);
                break;
            }

        }
        _is_running = false;
    }

    void HandleEvents(fd_set &rfds) // rfds就可能会有更多fd就绪
    {
        for (int i = 0; i < NUM; i++)
        {
            if (_fd_array[i] == gdefalutfd)
                continue;
            
            // 读事件分两类，一种是新连接到来，另一种是新数据到来
            int fd = _fds[i].fd;
            if(fd == _listen_socket->Fd())
            {
                if(_fds[i].events & POLLIN)
                {
                    InetAddr client;
                    int newfd = _listen_socket->Acceptor(&client);
                    if (newfd < 0)
                        return;
                    else
                    {
                        std::cout << "获得了一个新的连接: " << newfd << ", new client: " << client.Addr() << std::endl;
                        // 添加新的fd到poll中
                        int pos = -1;
                        for (int j = 0; j < MAX; j++)
                        {
                            if (_fds[j].fd == gdefalutfd)
                            {
                                pos = j;
                                break;
                            }
                        }
    
                        if (pos == -1)
                        {
                            LOG(LogLevel::ERROR) << "服务器已经满了...";
                            close(newfd);
                        }
    
                        if (pos < NUM)
                        {
                            _fds[pos].fd = newfd;
                            _fds[pos].events = POLLIN;
                        }
                        
                    }
                }

            }
            else
            {
                if(_fds[i].events & POLLIN)
                {
                    // 处理读事件
                    char buffer[1024];
                    ssize_t n = recv(_fds[i].fd, buffer, sizeof(buffer)-1, 0);
                    if(n > 0)
                    {
                        buffer[n] = '\0';
                        std::cout <<  "client# " << buffer << std::endl;
                        // 回显消息
                        std::string message = "ehco# ";
                        message += buffer;
                        send(_fd_array[i], message.c_str(), message.size(), 0); //bug
                    }
                    else if(n == 0)
                    {
                        LOG(LogLevel::DEBUG) << "客户端退出链接, sockfd: " << _fd_array[i];
                        close(fd);
                        _fds[i].fd = gdefalutfd;
                        _fds[i].events = 0; 
                        _fds[i].revents = 0; 
                    }
                    else
                    {
                        LOG(LogLevel::DEBUG) << "客户端读取链失败, sockfd: " << _fd_array[i];
                        close(fd);
                        _fds[i].fd = gdefalutfd;
                        _fds[i].events = 0; 
                        _fds[i].revents = 0; 
                    }
                }
            }
        }
    }

    ~PollServer()
    {
        
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listen_socket;
    bool _is_running;
    struct pollfd _fds[MAX];
};